from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func
from flask import session
from flask import request
from flask import redirect
from flask import flash
from flask import render_template
from werkzeug.utils import secure_filename
from app import app, db
from flask import Flask
from app import models
from app import forms
import shutil
import copy
import ast
import os

ALLOWED_EXTENSIONS = {'sb3', 'png', 'jpg', 'jpeg'}
path = os.getcwd()#获取当前路径
db.create_all()
action = ['收藏','点赞','取消收藏','取消点赞','评论','回复了']
def get_userid(username):
    user_id = models.User.query.filter_by(username=username).first() 
    user_id = user_id.id
    return user_id

def setfile(filename,file):
    f = open(filename, "w")
    f.write(file)
    f.close()

def addlist(data):

    #(data)
    return data

def get_author(data):
    author = []
    for project in data:
        u = models.User.query.get(project.author_id)
        try:
            u = u.username
        except:
            pass
        author.append(u)
    return author

def addmessage(Initiator_id,position,Recipient,action_type,action):
    message_data = models.message(Initiator_id=Initiator_id,position=position,Recipient=Recipient,action= int(action_type + action))
    db.session.add(message_data)
    db.session.commit()

def getmessage(user_id):
    message_data = models.message.query.filter_by(Recipient=user_id).all()

@app.route('/sendtoNights')
def sendtoNights():
    addmessage(1,4,4,1,1)
    return 'hehe'

# 网站首页
@app.route('/')
def index():
    username = session.get('username') # 获取用户的用户名
    data = models.scratch_project.query.limit(5).all()
    data = []
    item = None
    i = 0
    rows = models.scratch_project.query.count()
    while len(data) < 6:
        item = models.scratch_project.query.get(rows-i)
        if item != None:
            if item.status == "0":
                data.append(item)
        else:
            break
        i += 1
    data.reverse()
    author = get_author(data)
    return render_template('page/index.html',username = username, ProjectData =data,author=author)

# 退出登录
@app.route('/logout')
def logout():
    session['username'] = None
    return redirect('/')

# 注册页面
@app.route('/register', methods = ['GET', 'POST'])
def register():
    form = forms.register()
    username = session.get('username') # 获取用户的用户名
    if request.method == 'POST':# 判断是否提交表单
        if form.validate_on_submit():# 表单符合规则
            # 加入数据库
            data = form.data # 用户输入的数据
            if models.User.query.filter_by(username=data['username']).first() == None:
                UserData = models.User(
                    username = data["username"],
                    email = data["email"],
                    password = data["password"],
                    profiles = "介绍一下你自己"
                )
                db.session.add(UserData)
                db.session.commit()
                session['username'] = data["username"]
                db.session.close()
                return redirect('/')
            else:
                flash('该名称已被占用')
                db.session.close()
                return render_template('page/register.html', form = form, username = username)
        else:
            return render_template('page/register.html', form = form, username = username)
    else:
        return render_template('page/register.html', form = form, username = username)

# 登录页面
@app.route('/login', methods = ['GET', 'POST'])
def login():

    form = forms.login()
    username = session.get('username') # 获取用户的用户名
    if request.method == 'POST':# 判断是否提交表单
        if form.validate_on_submit():# 表单符合规则
            # 判断是否可以登录
            data = form.data
            UserData = models.User.query.filter_by(username=data['username']).first()
            if UserData == None:
                flash("用户名不存在")
            else:
                if UserData.password == data['password']:
                    session['username'] = data['username']
                    db.session.close()
                    return redirect('/')
                else:
                    flash("密码错误")
            db.session.close()
            return render_template('page/login.html', form = form, username = username)
        else:
            return render_template('page/login.html', form = form, username = username)
    else:
        return render_template('page/login.html', form = form, username = username)

# 我的作品页面
@app.route('/myproject/')
def myporject():
    username = session.get('username')
    user_id = get_userid(username)
    if username == None:
        return redirect('/')  
    else:
        index = request.args.get("page")
        if index == None:
            index = 1
        index = int(index)
        ProjectData = models.scratch_project.query.filter_by(author_id=user_id).order_by().paginate(page=index, per_page=4)
        if ProjectData == None:
            ProjectData = []
        else:
            paginate = ProjectData
            data = paginate.items
            #(data)
        author = get_author(data)
        #(author)
        return render_template('page/myproject.html', username = username, ProjectData =data,p=paginate,author=author)

# 玩作品页面
@app.route('/project/<project_id>',methods=['GET'])
def project(project_id):
    username = session.get('username') # 获取用户的用户名
    if username == None:
        return "登录后重试"
    user_id = get_userid(username)
    ProjectData = models.scratch_project.query.get(int(project_id))
    if ProjectData == None:
        return redirect('/') 
    status = ProjectData.status
    title = ProjectData.title
    profiles = ProjectData.profiles
    
    CollectionData = models.collection.query.filter_by(user_id=user_id).all()
    is_collection = "false"
    try:
        for Collection in CollectionData:
            if str(Collection.project_id) == project_id:
                is_collection = "true"
                break
    except:
        pass
    
    LoveData = models.love.query.filter_by(user_id=user_id).all()
    is_love = "false"
    try:
        for love in LoveData:
            if str(love.project_id) == project_id:
                is_love = "true"
                break
    except:
        pass

    ProjectData.see += 1
    project_author = models.User.query.get(ProjectData.author_id)
    project_author = project_author.username
    if ProjectData.author_id == user_id:
        is_author = 1
    else:
        is_author = 0
    db.session.commit()

    if status == '1':
        if project_author == username:
            return render_template('scratch/player.html', username=username, Project= ProjectData, is_love=is_love,is_collection=is_collection,project_author=project_author,is_author=is_author)
        else:
            return redirect('/')  
    else:
        return render_template('scratch/player.html', username=username, Project= ProjectData, is_love=is_love,is_collection=is_collection,project_author=project_author,is_author=is_author)
    #comment_data comment_item

@app.route('/editor/<project_id>',methods=['GET'])
def project_editor(project_id):

    ProjectData = models.scratch_project.query.get(int(project_id))
    username = session.get('username') # 获取用户的用户名
    status = ProjectData.status
    if username == None:
        return redirect('/')  
    else:
        user_id = get_userid(username)
        project_author_id = ProjectData.author_id
        if status == '0':
            is_share = 0
        else:
            is_share = 1
        if project_author_id == user_id:
            is_author = 1
        else:
            is_author = 0
        #(comment_reply)
        if status == '1':
            if project_author_id == user_id:
                return render_template('scratch/index.html', username=username,project_id=project_id,project_name=ProjectData.title,is_share=is_share,is_author=is_author)
            else:
                return redirect('/') 
        else:        
            return render_template('scratch/index.html', username=username,project_id=project_id,project_name=ProjectData.title,is_share=is_share,is_author=is_author)

@app.route('/save_project/<int:project_id>', methods = ['POST'])
def save_project(project_id):

    projectdata = models.scratch_project.query.get(int(project_id))
    project_id = str(project_id)
    username = session.get('username')
    user_id = get_userid(username)
    if projectdata.author_id == user_id:

        files = request.files
        project_file = files.get('project_file')
        cover_file = request.form.get('project_cover')
        project_name = request.form.get("project_name")
        projectdata.title = project_name
        projectdata.cover = cover_file
        db.session.commit()
        if project_file.filename != 'project_file.sb3':
            return "0"
        project_save_url = os.path.abspath(r'app/static/upload/project/'+ project_id +'.sb3')
        os.remove(project_save_url)
        project_file.save(os.path.abspath(app.config['UPLOAD_FOLDER']+'/project/'+project_id +'.sb3'))
        #cover_file.save(os.path.abspath(app.config['UPLOAD_FOLDER']+'/cover/'+project_id +'.png'))
    else:
        return "0"
    return "1"

@app.route('/Project_operation/<int:project_id>', methods = ['POST'])
def Project_operation(project_id):
    username = session.get('username') # 获取用户的用户名
    if username == None:
        return 'None'
    user_id = get_userid(username)
    projectdata = models.scratch_project.query.get(int(project_id))

    collection = request.form.get("collection")
    if collection == '1':
        if models.collection.query.filter_by(user_id=user_id,project_id=project_id).all() == []:
            projectdata.collection += 1
            db.session.add(models.collection(user_id=user_id,project_id=project_id))
            addmessage(user_id,project_id,projectdata.author_id,'1','0')
    elif collection == '0':
        if models.collection.query.filter_by(user_id=user_id,project_id=project_id).all() != []:
            projectdata.collection -= 1
            try:
                db.session.delete(models.collection.query.filter_by(user_id=user_id,project_id=project_id).first())
                addmessage(user_id,project_id,projectdata.author_id,'1','2')
            except:
                pass
    else:    
        love = request.form.get("love")
        if love == '1':
            if models.love.query.filter_by(user_id=user_id,project_id=project_id).all() == []:
                projectdata.love += 1
                db.session.add(models.love(user_id=user_id,project_id=project_id))
                addmessage(user_id,project_id,projectdata.author_id,'1','1')
        elif love == '0':
            if models.love.query.filter_by(user_id=user_id,project_id=project_id).all() != []:
                projectdata.love -= 1
                try:
                    db.session.delete(models.love.query.filter_by(user_id=user_id,project_id=project_id).first())
                    addmessage(user_id,project_id,projectdata.author_id,'1','3')
                except:
                    pass
    db.session.commit()
    return 'None'

@app.route('/newproject')
def New_Project():
    username = session.get('username') # 获取用户的用户名
    if username == None:
        return redirect('/')
    project_id = len(models.scratch_project.query.all()) + 1
    author_id = get_userid(username)
    cover = ''
    db.session.add(models.scratch_project(status=1,title='未命名',cover=cover,profiles='这个人很赖连简介都不写',author_id=author_id,love=0,collection=0,see=0))
    shutil.copyfile(os.path.abspath('app/templates/project/1.sb3'),os.path.abspath(app.config['UPLOAD_FOLDER']+'/project/'+str(project_id) +'.sb3'))
    db.session.commit()
    return redirect('/project/'+str(project_id))

@app.route('/share/<int:project_id>', methods = ['POST'])
def share(project_id):
    username = session.get('username') # 获取用户的用户名
    if username == None:
        return 'None'
    user_id = get_userid(username)
    projectdata = models.scratch_project.query.get(int(project_id))
    if projectdata.author_id == user_id:
        projectdata.status = 0
    db.session.commit()
    return 'None'

@app.route('/del/<int:project_id>')
def del_project(project_id):
    username = session.get('username') # 获取用户的用户名
    if username == None:
        return redirect('/')
    user_id = get_userid(username)
    projectdata = models.scratch_project.query.get(int(project_id))
    if projectdata.author_id == user_id:
        db.session.delete(projectdata)
        db.session.commit()
        return redirect('/myproject')
    return redirect('/myproject')

@app.route('/sendcomment', methods = ['POST'])
def sendcomment():
    text = request.form.get("text")
    place = request.form.get("place")
    username = session.get('username') # 获取用户的用户名
    if username == None:
        return 'None'
    if len(text) > 512:
        return '字符数过长（限制512）'
    user_id = get_userid(username)
    db.session.add(models.comment(user_id = str(user_id),text=text,place=place,reply=str([])))
    db.session.commit()
    return render_template('page/loading.html')

@app.route('/user/<int:user_id>', methods = ['GET'])
def user(user_id):
    username = session.get('username')
    if username == None:
        return '登录后重试'
    user_data = models.User.query.get(user_id)
    user_project = models.scratch_project.query.filter_by(author_id=user_data.id).all()
    author = get_author(user_project)
    return render_template('page/user.html',author=author, user_data=user_data,ProjectData=user_project,username=username)

@app.route('/user', methods = ['GET'])
def goto_user():
    username = session.get('username')
    if username == None:
        return '登录后重试'
    user_id = get_userid(username)
    return redirect('/user/'+str(user_id))

@app.route('/replycomment', methods = ['POST'])
def replycomment():
    username = session.get('username')
    if username == None:
        return 'None'
    text = request.form.get("text")
    reply_comment_id = int(request.form.get("reply_comment_id"))
    reply_user_id = int(request.form.get("reply_user_id"))
    user_id = get_userid(username)

    comments = models.comment.query.get(reply_comment_id)
    comments_data_list= list(eval(str(comments.reply)))
    comments_data_list.append([user_id,text,reply_user_id])
    print(comments_data_list)
    comments.reply=str(comments_data_list)
    db.session.commit()
    return render_template('page/loading.html')

@app.route('/Search', methods = ['GET'])
def Search():
    username = session.get('username')
    if username == None:
        return '登录后重试'
    key = request.args.get("key")
    index = 1
    index = request.args.get("inedx")
    if index == None:
        index = 1
    if index < 1:
        index = 1
    return_scratch_project = models.scratch_project.query.filter(models.scratch_project.title.like('%{keyword}%'.format(keyword=key))).paginate(page=index, per_page=8)
    paginate = return_scratch_project
    return_scratch_project_all = []
    for i in return_scratch_project.items:
        if i.status == '0':
            return_scratch_project_all.append(i)

    author = get_author(return_scratch_project_all)
    return render_template('page/search.html',username = username, ProjectData =return_scratch_project_all,author=author,p=paginate,index=int(index),key=key)

@app.route('/GetComment/<place>', methods = ['GET'])
def GetComment(place):
    username = session.get('username')
    if username == None:
        return 'None'
    index =request.args.get("page")
    if index == None:
        index = 1
    index = int(index)
    if index < 1:
        index = 1
    comment_reply = []
    comment_data = models.comment.query.filter_by(place=place).order_by(models.comment.id.desc()).paginate(page=index, per_page=8)
    p=comment_data
    comment_item = copy.deepcopy(comment_data.items)
    comment_user_id = []
    for i in range(len(comment_item)):
        comment_user_id_s = [comment_item[i].id,comment_item[i].user_id]
        user_id_name = models.User.query.get(int(comment_item[i].user_id))
        comment_item[i].user_id = user_id_name.username
        comment_item_add = eval(str(comment_item[i].reply))
        comment_item_add = list(comment_item_add)
        for j in range(len(comment_item_add)):
            comment_user_id_s.append(comment_item_add[j][0]) ##############################
            comment_item_add[j][0] = models.User.query.get(int(comment_item_add[j][0])).username
            comment_item_add[j][2] = models.User.query.get(int(comment_item_add[j][2])).username
        comment_user_id.append(comment_user_id_s)
        comment_reply.append(comment_item_add)
    return render_template('page/comments.html',index=index,projectID=place,comment_item=comment_item,comment_reply=comment_reply,comment_user_id=comment_user_id,p=p)

@app.route('/setprojectprofile', methods = ['POST'])
def setprojectprofile():
    username = session.get('username')
    if username == None:
        return 'None'
    user_id=get_userid(username)
    text = request.form.get("text")
    project_id = request.form.get("project_id")
    project_data = models.scratch_project.query.get(project_id)
    if project_data.author_id == user_id:
        if len(text) < 512:
            project_data.profile = text
            db.session.commit()
        else:
            return 'None'
    else:
        return 'None'

@app.route('/MyMessage', methods = ['GET'])
def MyMessage():
    username = session.get('username')
    if username == None:
        return 'None'
    index = request.args.get("page")
    if index == None:
        index = 1
    if index < 1:
        index = 1
    user_id=get_userid(username)
    message_data = models.message.query.filter_by(Recipient=user_id).paginate(page=index, per_page=8)
    print(message_data.items,index)
    message_data_item = message_data.items
    message_return_url = []
    return_item = []
    for message in message_data_item:

        return_action = str(message.action)[1:len(str(message.action))]
        return_type =  str(message.action)[0]
        return_action = action[int(return_action)]

        intitator_data = models.User.query.get(message.Initiator_id)
        Initiator_id_url = 'user/' + str(message.Initiator_id)
        return_Initiator = intitator_data.username 

        if return_type =='1':
            position_data = models.scratch_project.query.get(message.position)
            return_position = position_data.title
            position_id_url = 'prject/' + str(message.position)
        else:
            position_data = models.User.query.get(message.position)
            return_position = position_data.username
            position_id_url = 'user/' + str(message.position)

        print()
        message_return_url.append([Initiator_id_url,position_id_url])
        return_item.append([return_Initiator,return_position,return_action,return_type])
    return render_template('page/message.html',p=message_data,message_data_item=return_item,index=int(index),message_url=message_return_url)